
<template>
  <vxe-grid
    class="gird-header"
    ref="gird-header"
    cell-class-name="header-table-cell"
    align="center"
    border
    auto-resize
    resizable
    show-overflow
    :empty-text="emptyText"
    :mergeCells="mergeCells"
    :rowStyle="handleRowStyle"
    :maxHeight="maxHeight"
    :scroll-x="tableConfig.scrollX"
    :scroll-y="tableConfig.scrollY"
    :show-header="showHeader"
    :tooltip-config="{showAll:false,enterable:true}"
    v-bind="$attrs"
    v-on="$listeners"
  >
  </vxe-grid>
</template>

<script>
export default {
  name: "VirtualHeaderTable",

  props: {
    emptyText: {
      type: String,
      default: " ",
    },

    rowHeight: {
      type: Number,
      default: 50,
    },

    maxHeight: {
      type: Number,
      default: 200,
    },
  },

  data() {
    return {
      isExport: false, // 是否在导出
      showHeader: false,
      columnsLength: 0,
      mergeCells: [],
      tableConfig: {
        scrollX: {
          gt: 0,
          enabled: true,
        },
        scrollY: {
          gt: 0,
          enabled: true,
        },
      },
    };
  },

  methods: {
    async init(tableData) {
      await this.loadTable(tableData);
    },

    loadTable({ columns = [], data = [], mergeCells = [] }) {
      const instance = this.getInstance();
      return new Promise((resolve) => {
        this.mergeCells = Object.freeze(mergeCells);
        this.columnsLength = columns.length;
        if (instance) {
          Promise.all([
            instance.reloadColumn(columns),
            instance.reloadData(data),
          ]).then(resolve);
        }
      });
    },

    getColumnsLen() {
      return this.columnsLength;
    },

    getInstance() {
      return this.$refs["gird-header"];
    },

    // 设置行样式(为了解决虚拟滚动+合并单元格引起的bug----插件本身的bug)
    handleRowStyle() {
      return {
        height: `${this.rowHeight}px`,
      };
    },

    // 开启虚拟滚动
    async openVirtualScroll() {
      this.isExport = false;
      // 修改虚拟滚动配置
      this.tableConfig = {
        scrollX: {
          gt: 0,
          enabled: true,
        },
        scrollY: {
          gt: 0,
          enabled: true,
        },
      };
    },

    // 关闭虚拟滚动
    async closeVirtualScroll() {
      this.isExport = true;
      // 修改虚拟滚动配置
      this.tableConfig = {
        scrollX: {
          gt: 0,
          enabled: false,
        },
        scrollY: {
          gt: 0,
          enabled: false,
        },
      };
      return this.$nextTick();
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .header-table-cell {
  // background: rgba(244, 245, 250, 1);
  .vxe-cell--label {
    font-size: 12px;
    font-weight: 400;
  }
}
.gird-header ::v-deep .vxe-table--body-wrapper {
  overflow: hidden;
  // background: rgba(244, 245, 250, 1);
}
</style>